import { Button, Card, message, Modal, Table } from 'antd'
import React, { Component, Fragment } from 'react'
import moment from 'moment'
import { QuestionCircleOutlined } from '@ant-design/icons'
import LinkButton from '../../components/link-button'
import { adduser, getrole, getuser, edituser, deluser } from '../../api'
import Adduser from './adduser'
const { confirm } = Modal;
export default class index extends Component {
  state = {
    roles: [],
    users: [],
    showadduser: false,
    showdeluser: false,
    Modaltitle: 0,
    recordindex: 0,
  }
  columns = [
    {
      title: '用户名',
      dataIndex: 'username',
      width: '10%'
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      width: '20%'
    },
    {
      title: '电话',
      dataIndex: 'phone',
      width: '20%'
    },
    {
      title: '注册时间',
      dataIndex: 'create_time',
      width: '20%',
      render: value => value === undefined ? value : moment(value).format('YYYY年M月DD日 HH:mm:ss')
    },
    {
      title: '所属角色',
      dataIndex: 'role',
      width: '10%',
    },
    {
      title: '操作',
      width: '20%',
      render: (status, record, index) => (
        <Fragment>
          <LinkButton type='primary' onClick={this.showedituser(status, record, index)}>修改</LinkButton>&nbsp;
          <LinkButton type='primary' onClick={this.showdeluser(status, record, index)}>删除</LinkButton>
        </Fragment>
      )
    },
  ]
  AdduserRef = React.createRef()
  showadduser = () => {
    this.setState({ showadduser: true, Modaltitle: 0 })
  }
  onCancel = () => {
    this.setState({ showadduser: false })
  }
  onOk = async () => {
    const { users, roles, Modaltitle, recordindex } = this.state
    try {
      const value = await this.AdduserRef.current.validateFields()
      const { username, password, phone, email, role_id } = value
      const role = roles.find((role) => {
        return role._id === role_id
      })
      value.role = role ? role.name : ''

      if (Modaltitle === 0) {
        const result = await adduser(username, password, phone, email, role_id)
        if (result.status === 0) {
          message.success('添加成功！')
          value._id = result.data._id
          value.create_time = result.data.create_time
          this.setState({ showadduser: false, users: [...users, value] })
        } else {
          message.error(result.msg)
        }
      } else {
        const user = {
          _id: users[recordindex]._id, username, phone, email, role_id
        }
        if (password) {
          user.password = password
        }
        const result = await edituser(user)
        if (result.status === 0) {
          message.success('更新成功！')
          users[recordindex] = result.data
          const role = roles.find((role) => {
            return role._id === role_id
          })
          users[recordindex].role = role ? role.name : ''
          this.setState({ showadduser: false, users: [...users] })
        } else {
          message.error(result.msg)
        }
      }
    } catch (error) {
      error.errorFields.map((item) => {
        return (
          message.error(item.errors)
        )
      })
    }

  }
  showedituser = (status, record, index) => {
    return () => {
      this.setState({ recordindex: index, showadduser: true, Modaltitle: 1 })

    }
  }
  showdeluser = (status, record, index) => {
    return () => {
      const { users } = this.state
      this.setState({ recordindex: index, showdeluser: true })
      const deluser = this.deluser
      confirm({
        icon: <QuestionCircleOutlined />,
        content: <Fragment>是否删除{record.username}?</Fragment>,
        onOk() {
          deluser(record._id, users, index)
        },
      });
    }
  }
  deluser = async (id, users, index) => {
    const result = await deluser(id)
    if (result.status === 0) {
      message.success('删除成功！')
      const newusers=[]
      for (let i = 0; i < users.length; i++) {
        if (i !== index) {
          newusers.push(users[i])
        }
      }
        this.setState({ showadduser: false, users: newusers })
    } else {
      message.error(result.msg)
    }


  }
  async componentDidMount() {
    const result = await Promise.all([getrole(), getuser()])
    if (result[0].status === 0 && result[1].status === 0) {
      const { users } = result[1].data
      users.map((item, key) => {
        const role = result[0].data.find((role) => {
          return role._id === item.role_id
        })
        users[key].role = role ? role.name : ''
        return () => { }
      })
      this.setState({ roles: result[0].data, users: users })
    }
  }
  render() {
    const { users, showadduser, Modaltitle, roles, recordindex } = this.state
    const title = (<Button type='primary' children='创建用户' onClick={this.showadduser} />)
    return (
      <Card title={title} >
        <Table columns={this.columns} bordered dataSource={users} rowKey='_id'>
        </Table>
        <Modal visible={showadduser} title={Modaltitle === 0 ? '添加用户' : '修改用户'} onCancel={this.onCancel}
          onOk={this.onOk} destroyOnClose>
          <Adduser AdduserRef={this.AdduserRef} roles={roles} record={users[recordindex]} Modaltitle={Modaltitle}></Adduser>
        </Modal>
      </Card>
    )
  }
}
